/*
 * @Author: 星孑
 * @Date: 2022-04-09 11:21:20
 * @LastEditors: 星孑
 * @LastEditTime: 2022-04-09 14:37:38
 * @FilePath: /admin/src/store/modules/permission.js
 * @Description: 权限过滤
 */

import { asyncRoutes, defaultRoutes } from '@/router'

const filterRoutes = (routes, permissions) => {
  return routes.filter(item => {
    if (permissions.find(one => one.code === item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterRoutes(item.children, permissions)
      }
      return true
    } else {
      return false
    }
  })
}

const permission = {
  state: {
    routes: defaultRoutes,
    buttons: []
  },

  mutations: {
    SET_ROUTES(state, routes) {
      state.routes = [...defaultRoutes, ...routes]
    },
    SET_BUTTONS(state, buttons) {
      state.buttons = buttons
    }
  },

  actions: {
    // 用户名登录
    GenerateRoutes({ commit }, permissions) {
      return new Promise((resolve, reject) => {
        const routes = filterRoutes(asyncRoutes, permissions)
        const buttons = permissions.filter(item => item.level === 0)
        commit('SET_BUTTONS', buttons)
        commit('SET_ROUTES', routes)
        resolve(routes)
      })
    }
  }
}

export default permission
